package com.lagou.service.impl;

import com.lagou.dao.TokenDao;
import com.lagou.dao.UserDao;
import com.lagou.pojo.Token;
import com.lagou.pojo.User;
import com.lagou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;
    @Autowired
    TokenDao tokenDao;

    /**
     * 注册用户
     * @param user
     * @return
     */
    @Override
    public boolean regiestUser(User user) {
        User save = userDao.save(user);
        return true;
    }

    /**
     * 根据传入的邮箱，判断该邮箱是否已经注册
     * @param email
     * @return
     */
    @Override
    public boolean isRegiested(String email) {
        User user = new User();
        user.setEmail(email);
        Example<User> example = Example.of(user);
        boolean exists = userDao.exists(example);
        return exists;
    }

    /**
     * 根据传入的邮箱密码进行登录，登录成功返回token，失败返回null
     * @param email
     * @param password
     * @return
     */
    @Override
    public String login(String email, String password) {
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        Example<User> example = Example.of(user);
        //验证邮箱密码是否正确
        boolean exists = userDao.exists(example);
        if (exists){
            String token = UUID.randomUUID().toString();
            Token token1 = new Token();
            token1.setEmail(email);
            token1.setToken(token);
            tokenDao.save(token1);
            return token;
        }
        return null;
    }

    @Override
    public User getInfo(String token) {
        Token token1 = new Token();
        token1.setToken(token);
        Example<Token> example = Example.of(token1);
        List<Token> tokens = tokenDao.findAll(example);
        String email = tokens.get(0).getEmail();
        User user = new User();
        user.setEmail(email);
        List<User> users = userDao.findAll(Example.of(user));
        return users.get(0);
    }
}
